package com.yikes.srb.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yikes.srb.common.result.PageResult;
import com.yikes.srb.common.utils.object.BeanUtils;
import com.yikes.srb.leadingModle.form.borrower.*;
import com.yikes.srb.leadingModle.form.borrowerattach.BorrowerAttachAddForm;
import com.yikes.srb.leadingModle.vo.BorrowInfoVO;
import com.yikes.srb.leadingModle.vo.BorrowerAttachVO;
import com.yikes.srb.leadingModle.vo.BorrowerDetailVO;
import com.yikes.srb.leadingModle.vo.BorrowerVO;
import com.yikes.srb.mapper.UserInfoMapper;
import com.yikes.srb.mybatis.base.PageForm;
import com.yikes.srb.pojo.entity.Borrower;
import com.yikes.srb.mapper.BorrowerMapper;
import com.yikes.srb.pojo.entity.BorrowerAttach;
import com.yikes.srb.pojo.entity.UserInfo;
import com.yikes.srb.pojo.entity.UserIntegral;
import com.yikes.srb.pojo.enums.BorrowInfoStatusEnum;
import com.yikes.srb.pojo.enums.BorrowerStatusEnum;
import com.yikes.srb.pojo.enums.IntegralEnum;
import com.yikes.srb.service.BorrowerAttachService;
import com.yikes.srb.service.BorrowerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yikes.srb.service.DictService;
import com.yikes.srb.service.UserIntegralService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 借款人 服务实现类
 * </p>
 *
 * @author guanrong.yin
 * @since 2024-12-03
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class BorrowerServiceImpl extends ServiceImpl<BorrowerMapper, Borrower> implements BorrowerService {

    private final BorrowerAttachService borrowerAttachService;

    private final UserInfoMapper userInfoMapper;

    private final DictService dictService;

    private final UserIntegralService userIntegralService;


    @Override
    public PageResult<BorrowerVO> listPage(BorrowerQuery query) {

        Page<Borrower> page = lambdaQuery()
                .eq(ObjectUtil.isNotNull(query.getUserId()), Borrower::getUserId, query.getUserId())
                .like(StrUtil.isNotBlank(query.getName()), Borrower::getName, query.getName())
                .like(StrUtil.isNotBlank(query.getIdCard()), Borrower::getIdCard, query.getIdCard())
                .like(StrUtil.isNotBlank(query.getMobile()), Borrower::getMobile, query.getMobile())
                .eq(ObjectUtil.isNotNull(query.getSex()), Borrower::getSex, query.getSex())
                .eq(ObjectUtil.isNotNull(query.getAge()), Borrower::getAge, query.getAge())
                .eq(ObjectUtil.isNotNull(query.getEducation()), Borrower::getEducation, query.getEducation())
                .eq(ObjectUtil.isNotNull(query.getIsMarry()), Borrower::getIsMarry, query.getIsMarry())
                .eq(ObjectUtil.isNotNull(query.getIndustry()), Borrower::getIndustry, query.getIndustry())
                .eq(ObjectUtil.isNotNull(query.getReturnSource()), Borrower::getReturnSource, query.getReturnSource())
                .like(StrUtil.isNotBlank(query.getContactsName()), Borrower::getContactsName, query.getContactsName())
                .like(StrUtil.isNotBlank(query.getContactsMobile()), Borrower::getContactsMobile, query.getContactsMobile())
                .eq(ObjectUtil.isNotNull(query.getStatus()), Borrower::getStatus, query.getStatus())
                .page(Page.of(query.getPageNum(), query.getPageSize()));

        List<BorrowerVO> bean = BeanUtils.toBean(page.getRecords(), BorrowerVO.class);
        return PageResult.build(page.getTotal(), page.getPages(), bean);
    }

    @Override
    public BorrowerVO infoId(Long id) {

        Borrower borrower = getById(id);
        BorrowerVO bean = BeanUtils.toBean(borrower, BorrowerVO.class);
        return bean;

    }

    @Override
    public void create(BorrowerAddForm form) {

        Borrower bean = BeanUtils.toBean(form, Borrower.class);
        save(bean);
    }

    @Override
    public void edit(BorrowerEditForm form) {

        Borrower bean = BeanUtils.toBean(form, Borrower.class);
        updateById(bean);

    }

    @Override
    public void del(Long id) {

        baseMapper.deleteById(id);
    }

    @Override
    public void saveBorrowerVOByUserId(BorrowerForm form, Long userId) {

        UserInfo userInfo = userInfoMapper.selectById(userId);
        //保存借款人信息
        Borrower borrower = new Borrower();
        BeanUtils.copyProperties(form, borrower);
        borrower.setUserId(userId);
        borrower.setName(userInfo.getName());
        borrower.setIdCard(userInfo.getIdCard());
        borrower.setMobile(userInfo.getMobile());
        // 认证中
        borrower.setStatus(BorrowerStatusEnum.AUTH_RUN.getStatus());
        baseMapper.insert(borrower);

        //保存附件
        List<BorrowerAttachAddForm> borrowerAttachList = form.getBorrowerAttachList();
        List<BorrowerAttach> attachList = BeanUtils.toBean(borrowerAttachList, BorrowerAttach.class);
        attachList.forEach(attach -> attach.setBorrowerId(borrower.getId()));
        borrowerAttachService.saveBatch(attachList);

        //更新会员状态，更新为认证中
        userInfo.setBorrowAuthStatus(BorrowerStatusEnum.AUTH_RUN.getStatus());
        userInfoMapper.updateById(userInfo);
    }

    @Override
    public Integer getStatusByUserId(Long userId) {

        QueryWrapper<Borrower> borrowerQueryWrapper = new QueryWrapper<>();
        borrowerQueryWrapper.select("status").eq("user_id", userId);
        List<Object> objects = baseMapper.selectObjs(borrowerQueryWrapper);

        if (objects.isEmpty()) {
            //借款人尚未提交信息
            return BorrowerStatusEnum.NO_AUTH.getStatus();
        }
        return (Integer) objects.get(0);
    }

    @Override
    public BorrowerDetailVO getBorrowerDetailVOById(Long id) {

        // 获取借款人信息
        Borrower borrower = baseMapper.selectById(id);

        // 填充基本借款人信息
        BorrowerDetailVO detailVO = new BorrowerDetailVO();
        BeanUtils.copyProperties(borrower, detailVO);

        //婚否
        detailVO.setMarry(borrower.getIsMarry() == 1 ? "是" : "否");
        //性别
        detailVO.setSex(borrower.getSex() == 1 ? "男" : "女");

        //计算下拉列表选中内容
        String education = dictService.getNameByParentDictCodeAndValue("education", borrower.getEducation());
        String industry = dictService.getNameByParentDictCodeAndValue("moneyUse", borrower.getIndustry());
        String income = dictService.getNameByParentDictCodeAndValue("income", borrower.getIncome());
        String returnSource = dictService.getNameByParentDictCodeAndValue("returnSource", borrower.getReturnSource());
        String contactsRelation = dictService.getNameByParentDictCodeAndValue("relation", borrower.getContactsRelation());

        //设置下拉列表选中内容
        detailVO.setEducation(education);
        detailVO.setIndustry(industry);
        detailVO.setIncome(income);
        detailVO.setReturnSource(returnSource);
        detailVO.setContactsRelation(contactsRelation);

        //审批状态
        String status = BorrowerStatusEnum.getMsgByStatus(borrower.getStatus());
        detailVO.setStatus(status);

        //获取附件VO列表
        List<BorrowerAttachVO> borrowerAttachVOList = borrowerAttachService.selectBorrowerAttachVOList(id);
        if (CollUtil.isNotEmpty(borrowerAttachVOList)) {
            detailVO.setBorrowerAttachVOList(borrowerAttachVOList);
        }

        return detailVO;
    }

    @Override
    public void approval(BorrowerApprovalForm form) {

        //借款人认证状态
        Long borrowerId = form.getBorrowerId();
        Borrower borrower = baseMapper.selectById(borrowerId);
        borrower.setStatus(form.getStatus());
        baseMapper.updateById(borrower);

        Long userId = borrower.getUserId();
        UserInfo userInfo = userInfoMapper.selectById(userId);

        //添加积分
        UserIntegral userIntegral = new UserIntegral();
        userIntegral.setUserId(userId);
        userIntegral.setIntegral(form.getInfoIntegral());
        userIntegral.setContent("借款人基本信息");
        userIntegralService.save(userIntegral);

        int curIntegral = userInfo.getIntegral() + form.getInfoIntegral();
        if (form.getIsIdCardOk()) {
            curIntegral += IntegralEnum.BORROWER_IDCARD.getIntegral();
            userIntegral = new UserIntegral();
            userIntegral.setUserId(userId);
            userIntegral.setIntegral(IntegralEnum.BORROWER_IDCARD.getIntegral());
            userIntegral.setContent(IntegralEnum.BORROWER_IDCARD.getMsg());
            userIntegralService.save(userIntegral);
        }

        if (form.getIsHouseOk()) {
            curIntegral += IntegralEnum.BORROWER_HOUSE.getIntegral();
            userIntegral = new UserIntegral();
            userIntegral.setUserId(userId);
            userIntegral.setIntegral(IntegralEnum.BORROWER_HOUSE.getIntegral());
            userIntegral.setContent(IntegralEnum.BORROWER_HOUSE.getMsg());
            userIntegralService.save(userIntegral);
        }

        if (form.getIsCarOk()) {
            curIntegral += IntegralEnum.BORROWER_CAR.getIntegral();
            userIntegral = new UserIntegral();
            userIntegral.setUserId(userId);
            userIntegral.setIntegral(IntegralEnum.BORROWER_CAR.getIntegral());
            userIntegral.setContent(IntegralEnum.BORROWER_CAR.getMsg());
            userIntegralService.save(userIntegral);
        }

        userInfo.setIntegral(curIntegral);
        //修改审核状态
        userInfo.setBorrowAuthStatus(form.getStatus());
        userInfoMapper.updateById(userInfo);

    }

    @Override
    public PageResult<BorrowInfoVO> selectList(String keyword, PageForm page) {

        IPage<BorrowInfoVO> borrowInfoVOIPage = baseMapper.selectBorrowInfoList(Page.of(page.getPageNum(), page.getPageSize()), keyword);

        if (CollUtil.isEmpty(borrowInfoVOIPage.getRecords())) {
            return PageResult.build(0L, 0L, Collections.emptyList());
        }
        borrowInfoVOIPage.getRecords().forEach(borrowInfo -> {
            String returnMethod = dictService.getNameByParentDictCodeAndValue("returnMethod", Integer.valueOf(borrowInfo.getReturnMethod()));
            String moneyUse = dictService.getNameByParentDictCodeAndValue("moneyUse", Integer.valueOf(borrowInfo.getMoneyUse()));
            String status = BorrowInfoStatusEnum.getMsgByStatus(Integer.parseInt(borrowInfo.getStatus()));

            borrowInfo.setReturnMethod(returnMethod);
            borrowInfo.setMoneyUse(moneyUse);
            borrowInfo.setStatus(status);
        });

        PageResult<BorrowInfoVO> pageResult = PageResult.build(borrowInfoVOIPage.getTotal(), borrowInfoVOIPage.getCurrent(),
                borrowInfoVOIPage.getRecords());

        return pageResult;
    }
}
